package cn.domypay.back.main.impl;

import java.util.Iterator;
import java.util.List;
import cn.domypay.back.bean.DmpOrderInfo;
import cn.domypay.back.control.OrderControl;
import cn.domypay.back.exception.DoMyPayException;
import cn.domypay.back.log.DoMyPayLogger;
import cn.domypay.back.main.OrderMain;
import cn.domypay.back.thread.OrderThread;

public class OrderMainImpl implements OrderMain{

	private final static DoMyPayLogger logger = DoMyPayLogger.getLogger(OrderMainImpl.class);
	
	private OrderControl orderControl;
	
	private OrderThread orderThread;
	
	private static int max_count = 0;
	
	public void setOrderControl(OrderControl orderControl) {
		this.orderControl = orderControl;
	}
	
	public void runDealOrder() throws NumberFormatException, DoMyPayException, InterruptedException
	{
		List list = orderControl.getAcceptOrderList();
		
		Iterator iter = list.iterator();
		
		int i = 0;
		
		ThreadGroup ordersGroup = new ThreadGroup("order");
		//订单组处理
		while(iter.hasNext())
		{
			DmpOrderInfo dmpOrderInfo = (DmpOrderInfo)iter.next();
			
			orderThread = new OrderThread(ordersGroup, "order"+i, orderControl, dmpOrderInfo);
			
			orderThread.start();
			
			i++;
		}
		orderGroupDeal(ordersGroup);
	}
	
	/**
	 * 订单组处理暂停器
	 * @param group
	 * @return
	 * @throws InterruptedException
	 */
	private boolean orderGroupDeal(ThreadGroup group) throws InterruptedException
	{	
		/*
		 * 当线程组中不存在活跃线程的时候，退出发送等待
		 */
		if(0 != group.activeCount())
		{
			Thread.sleep(group.activeCount()*50);
			/**
			 * 当线程组中有活跃线程存在，根据活跃线程数，
			 * 计算出需要等待的时间， 并进行发送等待
			 */
			max_count = max_count < group.activeCount() ? max_count = group.activeCount(): max_count;
			if(group.activeCount() < max_count && 1 == group.activeCount())
			{
				try{
					group.destroy();
				}catch(Exception e){
					logger.logError(e.getMessage());
					return false;
				}
				
			}
			orderGroupDeal(group);
			return true;
		}
		return false;
	}
}
